/*
 * protocol_cli.c
 *
 *  Created on: 2012. 4. 6.
 *      Author: injoon
 */

#include "unp.h"

#define IDSIZE 20


int crlf_add(char *dst, int dstsize, const char *src, int lenin);
int crlfcrlf_add(char *dst, int dstsize, const char *src, int lenin);

int check_protocol(char *msg, int sockfd) {

	char *protocol;
	protocol = strtok(msg, " ");

	if (strcmp(protocol, "230")) { //USER

		printf("print user");
		return 1;

	}

	else if (strcmp(protocol, "200")) { // WHO , FROM
		printf("print who");
		return 2;

	}

	else if (strcmp(protocol, "299")) { //FROM
		printf("print from");
		return 3;
	}

	else if (strcmp(protocol, "221")) { // QUIT
		printf("print quit");
		Shutdown(sockfd, SHUT_WR); /* send FIN */
		return 4;
	}
}

void login(int sockfd, char* msg, char* userid) {
	char buf[MAXLINE];
	char id[20];

	memset(id, NULL, IDSIZE);
	memset(buf, NULL, MAXLINE);

	Writen(fileno(stdout), "ID : ", strlen("ID : "));

	Read(fileno(stdin), id, 20);
	sprintf(buf, "USER %s", id);

	crlf2_add(msg, MAXLINE + 50, buf, MAXLINE);
	Writen(sockfd, msg, strlen(msg));

	lf_strip(userid, IDSIZE, id, strlen(id));
	printf("userid : [%s]\n", userid);

	//strncpy(userid, id, strlen(id)-1);

}

void msgprotocol(char *myid, char* oppid, char* srcmsg, char* dstmsg) {

	char *p;
	char buf[MAXLINE+50];

	p = strtok(srcmsg, " ");

	if (strcmp(p, "/w") == 0){
		p = strtok(NULL, " "); // ID
		if (p) {
			oppid = p;
		}
		/*
		else if (p == NULL) {
		printf("ERROR typing -help");
		exit(1);
		}
		*/
		p = strtok(NULL, "NULL"); // message
		if (p) {
			sprintf(buf, "FROM %s TO %s\r\n%s\r\n\r\n", myid, oppid, p);
			//printf("msg : %s", buf);
		}
	}
/*
	else { // send to msg to ID before setting
		if (strlen(oppid)>0) {
			printf("22222222\n");

			sprintf(buf, "FROM %s TO %s\r\n%s", myid, oppid, msg);
			printf("msg : %s", msg);
			printf("buf : %s", buf);
		} else {
			printf("ERROR typing -help");
			exit(1);
		}
	}
	*/
}





/*
 *
 * void msgprotocol(char *myid, char* oppid, char* msg) {

	char *p;
	char buf[MAXLINE+50];

	p = strtok(msg, " ");

	if (strcmp(p, "/w") == 0) {
		p = strtok(NULL, " "); // ID
		if (p) {
			oppid = p;
		}
		 else if (p == NULL) {
		 printf("ERROR typing -help");
		 exit(1);
		 }
		p = strtok(NULL, "\nNULL"); // message
		if (p) {
			sprintf(buf, "FROM %s TO %s\r\n%s\r\n\r\n", myid, oppid, p);
			//printf("msg : %s", buf);
		}
	}
	else { // send to msg to ID before setting
		if (strlen(oppid)>0) {
			printf("22222222\n");

			sprintf(buf, "FROM %s TO %s\r\n%s", myid, oppid, msg);
			printf("msg : %s", msg);
			printf("buf : %s", buf);
		} else {
			printf("ERROR typing -help");
			exit(1);
		}
	}
}
 */

void make_protocol(char *msg) {
	sprintf(msg, "%s\r\n\r\n", msg);
}

